package com.blacktea.rabbitmq.springbootrabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 插件实现延迟队列
 * @description:
 * @author: black tea
 * @date: 2022/6/5 20:02
 */
//@Configuration
public class DelayedQueueConfig {

    /** 队列 **/
    public final static String DELAYED_QUEUE_NAME = "delayed.queue";

    /** 交换机 **/
    public final static String DELAYED_EXCHANGE_NAME = "delayed.exchange";

    /** routingKey **/
    public final static String DELAYED_ROUTING_KEY = "delayed.routingKey";

    /** 插件类型的交换机 **/
    public final static String EXCHANGE_TYPE = "x-delayed-message";

    @Bean
    public Queue delayedQueue(){

        return QueueBuilder
                .durable(DELAYED_QUEUE_NAME)
                .build();
    }

    @Bean
    public Exchange delayedExchange(){
        // String name, 交换机名称
        // String type, 交换机类型
        // boolean durable, 是否需要持久化
        // boolean autoDelete, // 是否需要自定删除
        // Map<String, Object> arguments // 其他的参数
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-delayed-type", "direct");

        return new CustomExchange(
                    DELAYED_EXCHANGE_NAME,
                    EXCHANGE_TYPE,
                    true,
                    false,
                    arguments
                );
    }

    @Bean
    public Binding delayedQueueBindingDelayedExchange(@Qualifier("delayedQueue") Queue delayedQueue,
                                                      @Qualifier("delayedExchange") CustomExchange delayedExchange){

        return BindingBuilder
                .bind(delayedQueue)
                .to(delayedExchange)
                .with(DELAYED_ROUTING_KEY)
                .noargs();
    }

}
